package top.api.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import top.api.Constants.SystemConstants;
import top.api.common.ResponseResult;
import top.api.domain.entity.LoginUserDetails;
import top.api.domain.entity.User;
import top.api.service.AdminLoginService;
import top.api.utils.JwtUtil;
import top.api.utils.RedisCache;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class AdminLoginServiceImpl implements AdminLoginService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        // 他会调用UserDetailsService里面的loadUserByUsername方法进行认证,所以需要我们自己重写认证规则
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 貌似不需要在这里判断,如果错误在内部过滤器会抛出异常
        // 判断是否认证通过
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }

        // 获取userId生成jwt
        LoginUserDetails loginUser = (LoginUserDetails) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();

        String jwt = JwtUtil.createJWT(userId);
        // 将用户信息存入redis
        redisCache.setCacheObject(SystemConstants.REDIS_LOGIN_ADMIN_KEY +userId,loginUser);

        // Vo拷贝
        Map<String,String> map = new HashMap<>();
        map.put("token",jwt);

        return ResponseResult.okResult(map);
    }
}
